/**
 * 猎头发布预览
 */
import React from 'react';
import { PageContainer } from '@/molecules';
import FileUpload from '@/components/Custom/FileUpload';
import { Form, Button, Input, message, Select, Spin } from 'antd';
import { history } from 'umi';
import { BottomAction } from '@/components';
import { customUpload } from '@/utils/fileUpload';
import BraftEditor from 'braft-editor';
import { useRequest, defaultFormatResult } from '@/hooks';
import { sameTabProps } from '@/utils/tab';
import { DemandFieldUpdate } from '@/pages/Recruitment/Channel/containers';
import { transformFileList } from '../utils';
import { getRecruitHunterChannelDetail, updateRecruitHunterChannelDetail } from '../service';

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
    }
};
const infoTypeList = [
    { value: 1, text: '岗位发布/上线时发送的邮件模板' },
    { value: 2, text: '岗位更新时发送的邮件模板' },
    { value: 3, text: '岗位下线时发送的邮件模板' }
];
const { Option } = Select;
const HeadHunterPreviewForm = ({ form, location }) => {
    const {
        query: { code: channelCode, outwardId, recruitId }
    } = location;
    const { getFieldDecorator, validateFieldsAndScroll, getFieldValue, setFieldsValue } = form;
    const currInfoType = getFieldValue('infoType') || 1;
    const { data, loading, run: runData } = useRequest(
        () => {
            if (outwardId && channelCode && currInfoType) {
                return getRecruitHunterChannelDetail(channelCode, outwardId, currInfoType);
            }
            return null;
        },
        {
            refreshDeps: [outwardId, channelCode, currInfoType],
            ...defaultFormatResult
        }
    );
    const { loading: submitLoading, run: runSubmit } = useRequest(
        formData => updateRecruitHunterChannelDetail(outwardId, formData),
        {
            manual: true,
            onSuccess: d => {
                const { code, msg } = d;
                if (code === 10000) {
                    message.success(msg);
                    history.push({
                        pathname: '/office/personnelManagement/recruitment/channel',
                        query: { recruitCode: recruitId },
                        ...sameTabProps
                    });
                } else {
                    message.error(msg);
                }
            }
        }
    );
    // 不允许添加尺寸大于10M的文件
    const myValidateFn = file => {
        if (file.size > 1024 * 1024 * 10) {
            message.error('图片不能大于10M！');
            return false;
        }
        return true;
    };

    const myUploadFn = param => {
        const onSuccess = (response, file) =>
            param.success({
                url: response.data[0].url,
                meta: {
                    id: file.name,
                    title: file.name,
                    alt: file.name
                }
            });
        customUpload({ files: param, onSuccess });
    };

    const controls = [
        'undo',
        'redo',
        'separator',
        'font-size',
        'line-height',
        'letter-spacing',
        'separator',
        'text-color',
        'bold',
        'italic',
        'underline',
        'strike-through',
        'separator',
        'superscript',
        'subscript',
        'remove-styles',
        'emoji',
        'separator',
        'text-indent',
        'text-align',
        'separator',
        'headings',
        'list-ul',
        'list-ol',
        'blockquote',
        'code',
        'separator',
        'media',
        'link',
        'hr',
        'separator',
        'clear'
    ];
    const handleSubmit = () => {
        validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const { channelRecruitSubject, channelRecruitContent, resourceRelation, infoType } = values;
                const finalContent = channelRecruitContent.toHTML().replace('a href', 'a style="color:#FFA22D" href');
                const finalAttachment = resourceRelation?.uploadResourceFile
                    ? [resourceRelation?.uploadResourceFile]
                    : [];
                runSubmit({
                    channelCode,
                    channelRecruitSubject,
                    channelRecruitContent: finalContent,
                    resourceRelation: finalAttachment,
                    infoType
                });
            }
        });
    };
    React.useEffect(() => {
        if (data) {
            const { channelRecruitSubject, channelRecruitContent, channelRecruitAttachmentList } = data;
            setFieldsValue({
                channelRecruitSubject,
                channelRecruitContent: channelRecruitContent
                    ? BraftEditor.createEditorState(channelRecruitContent)
                    : BraftEditor.createEditorState(''),
                resourceRelation: transformFileList(channelRecruitAttachmentList)
            });
        }
    }, [data]);
    return (
        <Spin spinning={loading}>
            <DemandFieldUpdate style={{ margin: 16, marginBottom: -16 }} onRefresh={runData} outwardId={outwardId} />
            <PageContainer
                bordered={false}
                title={<div style={{ margin: '10px 0' }}>渠道发布信息</div>}
                extra={
                    data?.channelLogoUrl && (
                        <img height="44" src={data?.channelLogoUrl || ''} alt={data?.channelName || '猎头'} />
                    )
                }
            >
                <BottomAction>
                    <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                        提交
                    </Button>
                </BottomAction>
                <Form {...formItemLayout} className="ant-advanced-search-form">
                    <Form.Item label="发送模版">
                        {getFieldDecorator('infoType', {
                            initialValue: 1,
                            rules: [
                                {
                                    required: true,
                                    message: '请选择模版'
                                }
                            ]
                        })(
                            <Select
                                placeholder="请选择通知模版"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                            >
                                {infoTypeList.map(item => (
                                    <Option value={item.value} key={item.value}>
                                        {item.text}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label="主题">
                        {getFieldDecorator('channelRecruitSubject', {
                            rules: [
                                {
                                    required: true,
                                    message: '主题不能为空'
                                }
                            ]
                        })(<Input placeholder="请输入主题" allowClear maxLength={100} />)}
                    </Form.Item>

                    <Form.Item label="内容">
                        {getFieldDecorator('channelRecruitContent', {
                            initialValue: BraftEditor.createEditorState(),
                            validateTrigger: ['onChange'],
                            rules: [
                                {
                                    required: true,
                                    message: '内容不能为空'
                                },
                                {
                                    validator: (_, value, callback) => {
                                        if (value.isEmpty()) {
                                            callback('内容不能为空');
                                        } else if (value.toHTML().length > 20000) {
                                            callback('内容过多');
                                        } else {
                                            callback();
                                        }
                                    }
                                }
                            ]
                        })(
                            <BraftEditor
                                media={{
                                    uploadFn: myUploadFn,
                                    validateFn: myValidateFn,
                                    accepts: {
                                        image: 'image/png,image/jpeg,image/gif'
                                    }
                                }}
                                placeholder="请输入邮件内容"
                                controls={controls}
                                excludeControls={['fullscreen']}
                                imageControls={[
                                    {
                                        onClick: block => {
                                            console.log(block);
                                        } // 指定控件点击后的回调，参数为当前图片的block对象
                                    },
                                    'align-left',
                                    'align-center',
                                    'align-right',
                                    'size',
                                    'remove'
                                ]}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="附件">
                        {getFieldDecorator('resourceRelation')(
                            <FileUpload
                                checkFileSizeMsg="文件大小不能超过50MB！"
                                checkFileSize={50}
                                categoryCode="recruitChannelTemplateAttachmentFile"
                                checkFileType="TXT,DOC,DOCX,XLS,XLSX,PPT,PPTX,PDF,EDC,SSP,DWG,EDCS,
                            BMP,JPG,PNG,TIF,GIF,PCX,TGA,EXIF,FPX,SVG,PSD,CDR,PCD,DXF,UFO,EPS,AI,
                            RAW,WMF,WEBP,Xmind,ZIP,rar,zip,CAB,ARJ,LZH,TAR,GZ,ACE,UUE,BZ2,JAR,ISO,rp"
                                checkFileTypeMsg="附件格式不合规，请确认！"
                            >
                                <Button>添加附件</Button>
                            </FileUpload>
                        )}
                    </Form.Item>
                </Form>
            </PageContainer>
        </Spin>
    );
};
export default Form.create({})(HeadHunterPreviewForm);
